package com.vimi8.ebb.auth.api;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import com.vimi8.ebb.auth.configuration.HttpResponseEntity;
import com.vimi8.ebb.auth.configuration.OAuth2AuthenticationImpl;
import com.vimi8.ebb.auth.dto.AuthUserDto;
import com.vimi8.ebb.auth.dto.UserDto;
import com.vimi8.ebb.auth.manage.UserManageImpl;
import com.vimi8.ebb.auth.model.*;
import com.vimi8.ebb.auth.model.Error;
import com.vimi8.ebb.auth.service.*;
import com.vimi8.ebb.auth.utils.CommonUtil;
import com.vimi8.ebb.auth.utils.IdcardUtils;
import com.vimi8.ebb.auth.utils.PagesUtil;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONArray;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.security.oauth2.client.http.OAuth2ErrorHandler;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-09-12T05:17:54.080Z")

@Controller
class UserApiController implements UserApi {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    private String host="127.0.0.1";
    @Value("${server.contextPath}")
    private String contextPath;
    @Value("${server.port}")
    private String port;

    @Value("${verifycode.sms.company}")
    private String company;
    @Value("${verifycode.sms.tplid}")
    private String tplid;
    @Value("${verifycode.sms.smskey}")
    private String smskey;
    @Value("${verifycode.session.timeout}")
    private int verify_code_timeout;
    @Value("${verifycode.session.key}")
    private String verify_code_key;
    @Value("${verifycode.session.date}")
    private String verify_code_date;

    @Value("${verifycode-me.session.timeout}")
    private int verify_code_me_timeout;
    @Value("${verifycode-me.session.key}")
    private String verify_code_me_key;
    @Value("${verifycode-me.session.date}")
    private String verify_code_me_date;

//    @Value("${verifycode.char.string}")
//    private String verify_code_char_string;

    private Producer kaptchaProducer;
    Config config;
    @Autowired
    UserAuthorityService userAuthorityService;
    @Autowired
    private DBClientDetailsService dbClientDetailsService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private GeoCodingsService geoCodingsService;

    @Autowired
    private DBUserDetailsService dbUserDetailsService;
    @Autowired
    private UserManageImpl userManage;
    public UserApiController() {
        Properties props = new Properties();
        props.put("kaptcha.border", "no");
        props.put("kaptcha.textproducer.font.color", "black");
        props.put("kaptcha.textproducer.char.space", "5");
        //props.put("kaptcha.textproducer.char.string", verify_code_char_string);

        props.put("kaptcha.textproducer.char.string", "0123456789");
        config = new Config(props);
        kaptchaProducer = config.getProducerImpl();
    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();
    }

    public HttpResponseEntity<String> userCodesPost(@ApiParam(value = "验证码发送的目标手机号.", required = true) @RequestParam(value = "phoneNumber", required = true) String phoneNumber


            ,
                                                    @ApiParam(value = "发起调用的客户端id.", required = false) @RequestParam(value = "clientId", required = false) String clientId

            , HttpServletRequest request

    ) {
        // do some magic!
        HttpResponseEntity<String> response = null;
        Error error = null;
        String authCode = kaptchaProducer.createText();
        String tplValue = "";
        if (phoneNumber == null || !isMobileNO(phoneNumber)) {
            error = new Error().error("phone_number_error").errorDescription("phoneNumber is not MobileNO.");
            return new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
        }
        int count = 0;
        if (!StringUtils.isEmpty(clientId)) { //clientId为空代表是注册流程,需要的验证码
            count = userAuthorityService.getResourceClientUserCountByPhoneNumber(phoneNumber, clientId);
            if (count == 0) {
                error = new Error().error("phone_number_not_permission").errorDescription("phoneNumber is not permission.");
                return new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
            }
            Integer authCodeTimestampDiff = userAuthorityService.getAuthCodeTimestampDiff(phoneNumber);
            if (authCodeTimestampDiff != null && authCodeTimestampDiff <= verify_code_timeout) {
                error = new Error().error("operate_too_fast").errorDescription("verify code is already sent.");
                return new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
            }
        } else if ((request.getSession().getAttribute(verify_code_date) != null
                && (new Date().getTime() - ((Date) request.getSession().getAttribute(verify_code_date)).getTime()) < verify_code_timeout * 60000)) {
            error = new Error().error("operate_too_fast").errorDescription("verify code is already sent.");
            return new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
        }


        try {
            tplValue = URLEncoder.encode("#code#=" + authCode + "&#company#=" + company + "", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return new HttpResponseEntity<String>(new Error().error("encoder_error").errorDescription(e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }
        //http://v.juhe.cn/sms/send?mobile=手机号码&tpl_id=短信模板ID&tpl_value=%23code%23%3D654654&key=
        String url = "http://v.juhe.cn/sms/send?mobile=" + phoneNumber + "&tpl_id=" + tplid + "&tpl_value=" + tplValue + "&key=" + smskey;
        //logger.debug("--url:"+url);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new OAuth2ErrorHandler(new BaseOAuth2ProtectedResourceDetails()));
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        //logger.debug("--responseString:"+responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            if (!StringUtils.isEmpty(clientId)) {//clientId为空代表是注册流程,需要的验证码
                //记录发送的验证码,使用时,可检查时间间隔,如3分钟内有效
                count = userAuthorityService.updateUserDetailsForAuthCode(phoneNumber, authCode);
            } else {
                count = 1;
                //手机验证码绑定手机
//                logger.debug("----"+"session="+phoneNumber+authCode);
//                logger.debug("----"+"session="+new Date().getTime());
                request.getSession().setAttribute(verify_code_key,phoneNumber + authCode);
                request.getSession().setAttribute(verify_code_date, new Date());
            }
            return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
        } else {
            return new HttpResponseEntity<String>(new Error().error("response_status_error").errorDescription(responseEntity.getStatusCode() + ""), HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 发送手机号 验证原手机号码
     * @param clientId
     * @param request
     * @return
     */
    @Override
    public HttpResponseEntity<String> userCodesPost1( HttpServletRequest request) {
        HttpResponseEntity<String> response = null;
        Error error = null;
        String authCode = kaptchaProducer.createText();
        String tplValue = "";
        String openId = OAuth2AuthenticationImpl.openId();

        //根据当前登录用户openid查询手机号并发送验证码
        String phoneNumber = userAuthorityService.getPhoneNumberByOpenId(openId);
        logger.debug("----"+"phone_number="+phoneNumber);

        if (phoneNumber == null || !isMobileNO(phoneNumber)) {
            error = new Error().error("phone_number_error").errorDescription("phoneNumber is not MobileNO.");
            return new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
        }
        int count = 0;
       if ((request.getSession().getAttribute(verify_code_me_date) != null
                && (new Date().getTime() - ((Date) request.getSession().getAttribute(verify_code_me_date)).getTime()) < verify_code_me_timeout * 60000)) {
            error = new Error().error("operate_too_fast").errorDescription("verify code is already sent.");
            return new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
        }


        try {
            tplValue = URLEncoder.encode("#code#=" + authCode + "&#company#=" + company + "", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return new HttpResponseEntity<String>(new Error().error("encoder_error").errorDescription(e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }
        //http://v.juhe.cn/sms/send?mobile=手机号码&tpl_id=短信模板ID&tpl_value=%23code%23%3D654654&key=
        String url = "http://v.juhe.cn/sms/send?mobile=" + phoneNumber + "&tpl_id=" + tplid + "&tpl_value=" + tplValue + "&key=" + smskey;
        //logger.debug("--url:"+url);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new OAuth2ErrorHandler(new BaseOAuth2ProtectedResourceDetails()));
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        //logger.debug("--responseString:"+responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
                //记录发送的验证码,使用时,可检查时间间隔,如3分钟内有效
                count = 1;
                //手机验证码绑定手机
                logger.debug("----"+"session_me="+phoneNumber+authCode);
                logger.debug("----"+"session_me="+new Date().getTime());
                request.getSession().setAttribute(verify_code_me_key,authCode);
                request.getSession().setAttribute(verify_code_me_date, new Date());

            return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
        } else {
            return new HttpResponseEntity<String>(new Error().error("response_status_error").errorDescription(responseEntity.getStatusCode() + ""), HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param code
     * @param request
     * @return
     */
    public HttpResponseEntity<String> userPasswordPut(
            @ApiParam(value = "旧密码.", required = false) @RequestParam(value = "oldPassword", required = false) String oldPassword,
            @ApiParam(value = "新密码.", required = true) @RequestParam(value = "newPassword", required = true) String newPassword,
            @ApiParam(value = "verifyCode.", required = false) @RequestParam(value = "verifyCode", required = false) String verifyCode,
            HttpServletRequest request


    ) {
        Error error = null;
        int count = 0;
        try {
            //如果旧密码不为空 则直接根据旧密码修改  否则比较验证码是否正确
            if(oldPassword!=null&&!"".equals(oldPassword)){
                count = userAuthorityService.updatePassword(OAuth2AuthenticationImpl.clientId(), OAuth2AuthenticationImpl.openId(), oldPassword, newPassword);
            }else{
                logger.info("----- verify_code_me_key:"+request.getSession().getAttribute(verify_code_me_key));
                if((new Date().getTime() - ((Date) request.getSession().getAttribute(verify_code_me_date)).getTime()) > verify_code_me_timeout * 60000){
                    error=new Error().error("invalid_param").errorDescription("verify code timeout");
                    return new HttpResponseEntity<String>(error,HttpStatus.BAD_REQUEST);
                }
                if(!request.getSession().getAttribute(verify_code_me_key).equals(verifyCode)){
                    error=new Error().error("check_code").errorDescription("verify code is not right");
                    return new HttpResponseEntity<String>(error,HttpStatus.BAD_REQUEST);
                }
                //如果上面验证没错  就根据openId修改密码
                count = userAuthorityService.updatePasswordByOpenId(OAuth2AuthenticationImpl.clientId(),OAuth2AuthenticationImpl.openId(),newPassword);

            }

        } catch (Exception e) {
            return new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    public HttpResponseEntity<Token> userPost(

            @ApiParam(value = "个人的注册信息", required = true) @RequestBody RegUser regUser
            , HttpServletRequest request
    ) {
        Error error = new Error().error("invalid_param").errorDescription("param is empty");
        if (regUser != null) {
            //不信任客户端传递的uid
            regUser.setUserId(UUID.randomUUID().toString());
            if (StringUtils.isEmpty(regUser.getUserName()) || "string".equals(regUser.getUserName())) {
                regUser.setUserName(null);
            }

            if ((StringUtils.isEmpty(regUser.getIdCard()) && StringUtils.isEmpty(regUser.getUserName()))
                    || StringUtils.isEmpty(regUser.getPhoneNumber())
                    || StringUtils.isEmpty(regUser.getApplyClientId()) //必须要有ClientId
                    || regUser.getApplyClientId().size() == 0
                    || StringUtils.isEmpty(regUser.getPassword())) {
                error.error("invalid_param").errorDescription("required param is empty");
            } else if (regUser.getPhoneNumber() != null && !isMobileNO(regUser.getPhoneNumber())) {
                error.error("invalid_param").errorDescription("phoneNumber validate failed.");
            }else if(userAuthorityService.getUserPhoneNumberCount(regUser.getPhoneNumber())>=1){
                error = new Error().error("phone_number_is_exists").errorDescription("phone number is xists");
                return new HttpResponseEntity<Token>(error, HttpStatus.BAD_REQUEST);
            }else if (regUser.getIdCard() != null && !IdcardUtils.validateIdCard18(regUser.getIdCard())) {
                error.error("invalid_param").errorDescription("idCard validate failed.");
            }else if(userAuthorityService.getUseridCardCount(regUser.getIdCard())>=1){
                error = new Error().error("id_card_is_exists").errorDescription("id_card is exists");
                return new HttpResponseEntity<Token>(error, HttpStatus.BAD_REQUEST);
            }else if (StringUtils.isEmpty(regUser.getVerifyCode()) ||
                    !(regUser.getPhoneNumber() + regUser.getVerifyCode()).equals(request.getSession().getAttribute(verify_code_key))
                    ) {
                //logger.debug("----"+user.getPhoneNumber()+user.getAuthCode()+"!="+request.getSession().getAttribute(verify_code_key));
                error.error("invalid_param").errorDescription("invalid verify code");
            } else if ((request.getSession().getAttribute(verify_code_date) != null
                    && (new Date().getTime() - ((Date) request.getSession().getAttribute(verify_code_date)).getTime()) > verify_code_timeout * 60000)) {
                //短信验证码,有效期180秒
                //logger.debug("----"+new Date().getTime()+"-"+((Date)request.getSession().getAttribute(verify_code_date)).getTime()+"="+(new Date().getTime()-((Date)request.getSession().getAttribute(verify_code_date)).getTime()));
                error.error("invalid_param").errorDescription("verify code timeout");
            } else {
                int isCreatUser= 0;
                try {
                    isCreatUser = userManage.registerUser(regUser);
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    error.error("register error ").errorDescription(e.getMessage());
                    return new HttpResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
                }
                HttpResponseEntity<String> response=null;
                HttpHeaders responseHttpHeaders=new HttpHeaders();
                responseHttpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
                ClientDetails clientDetails = null;
                try {
                    clientDetails = dbClientDetailsService.getClientDetailsByClientId(regUser.getDefaultClientId());
                    if(clientDetails==null){
                        error.error("invalid_param").errorDescription("invalid client id");
                    }
                } catch (Exception ex) {
                    error.error("invalid_param").errorDescription(ex.getLocalizedMessage());
                }
                String loginName= StringUtils.isEmpty( regUser.getUserName())?(StringUtils.isEmpty(regUser.getIdCard())?regUser.getPhoneNumber():regUser.getIdCard()):regUser.getUserName();
                //检查是否创建用户成功,不成功,则代表所有申请的clientId都未找到,是非法的
                if(isCreatUser>0&&clientDetails != null){
                    //检查clienid是否有效
                        RestTemplate restTemplate = new RestTemplate();
                        restTemplate.setErrorHandler(new OAuth2ErrorHandler(new BaseOAuth2ProtectedResourceDetails()));
                        HttpHeaders restHeader = new HttpHeaders();
                        restHeader.setContentType(MediaType.APPLICATION_JSON_UTF8);
                        restHeader.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
                        restHeader.add("Authorization", "Basic " + CommonUtil.getBASE64(clientDetails.getClientId() + ":" + clientDetails.getClientSecret()));
                        String tokenUrl = String.format("/token?grant_type=password&username=%s&password=%s", loginName, regUser.getPassword());
                        tokenUrl = request.getScheme() + "://" + host + ":" + port + contextPath + tokenUrl;
                        HttpEntity<Void> formEntity = new HttpEntity<Void>(restHeader);
                        //logger.debug("---------tokenUrl:--------" + tokenUrl);
                        Token token = restTemplate.postForObject(tokenUrl, formEntity, Token.class);
                        token.setClientId(regUser.getDefaultClientId());
                        //logger.debug("---------token:--------" + token);
                        responseHttpHeaders.add("SET-COOKIE", "Authorization=bearer%20" + token.getAccess_token() + ";expire=" + new Date((new Date().getTime()) + token.getExpires_in() * 1000) + ";path=/;HttpOnly");
                        return new HttpResponseEntity<Token>(token, responseHttpHeaders, HttpStatus.OK);
                  //  return new HttpResponseEntity<Token>(count + "", HttpStatus.OK);
                }
                error.error("invalid_param").errorDescription("all apply clientId is not find");
            }
        }

        return new HttpResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }

    public HttpResponseEntity<String> userPut(

            @ApiParam(value = "需要更新的个人信息", required = true) @RequestBody AuthUserDto authUserDto

    ) {
        int count = 0;
        try {
            if (authUserDto.getIdCard() != null && IdcardUtils.validateIdCard18(authUserDto.getIdCard())) {
                count += userAuthorityService.updateIdCard(OAuth2AuthenticationImpl.clientId(), OAuth2AuthenticationImpl.openId(), authUserDto.getIdCard());
            }
            if (authUserDto.getUserName() != null && !"string".equals(authUserDto.getUserName())) {
                count += userAuthorityService.updateUserName(OAuth2AuthenticationImpl.clientId(), OAuth2AuthenticationImpl.openId(), authUserDto.getUserName());
            }
            if (authUserDto.getPhoneNumber() != null && isMobileNO(authUserDto.getPhoneNumber())) {
                count += userAuthorityService.updatePhoneNumber(OAuth2AuthenticationImpl.clientId(), OAuth2AuthenticationImpl.openId(), authUserDto.getPhoneNumber());
            }

            if (authUserDto.getRealName() != null&&authUserDto.getAddressCode()!=null&&authUserDto.getAddressDetail()!=null) {
                count += userAuthorityService.updateHeadImgAndAddress(authUserDto.getRealName(),authUserDto.getAddressCode(),authUserDto.getAddressDetail(),OAuth2AuthenticationImpl.clientId(), OAuth2AuthenticationImpl.openId());
            }
            if (authUserDto.getHeadImg() != null) {
                count += userAuthorityService.updateHeadImg(authUserDto.getHeadImg(),OAuth2AuthenticationImpl.clientId(), OAuth2AuthenticationImpl.openId());
            }
            if (authUserDto.getNickName() != null && !"string".equals(authUserDto.getNickName())) {
                count += userAuthorityService.updateNickName(OAuth2AuthenticationImpl.clientId(), OAuth2AuthenticationImpl.openId(), authUserDto.getNickName());
            }
        } catch (Exception e) {
            return new HttpResponseEntity<String>(new Error().error("sql_error").errorDescription(e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<AuthUserDto> userMeGet() {
        String clientId=OAuth2AuthenticationImpl.clientId();
        String openId=OAuth2AuthenticationImpl.openId();
        logger.info("openId=="+openId);
        AuthUserDto authUserDto= null;
        try {
            authUserDto = userAuthorityService.getAuthUserDtoByOpenid(openId,clientId);
            String userId=userAuthorityService.getUserIdByOpenId(openId);
            List<UserOrg> userOrgs=userAuthorityService.getUserOrgByUserId(userId);//加入农场

            List<UserOrg> followOrgs = userAuthorityService.getFollowUserOrgByOpenId(openId);//关注农场
            authUserDto.setJoinUserOrg(userOrgs);
            authUserDto.setFollowUserOrg(followOrgs);

        } catch (Exception e) {
            return new HttpResponseEntity<AuthUserDto>(new Error().error("sql_error").errorDescription(e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }

        return new HttpResponseEntity<AuthUserDto>(authUserDto, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<AuthUserDto> userGet(@ApiParam(value = "clientId", required = false) @RequestParam(value = "clientId", required = false) String clientId, @ApiParam(value = "openId", required = false) @RequestParam(value = "openId", required = false) String openId) {

        logger.info("openId=="+openId);
        if(StringUtils.isEmpty(clientId)){
            clientId=OAuth2AuthenticationImpl.clientId();
        }
        if(StringUtils.isEmpty(openId)){
            openId=OAuth2AuthenticationImpl.openId();
        }
        AuthUserDto authUserDto= null;
        try {
            authUserDto = userAuthorityService.getAuthUserDtoByOpenid(openId,clientId);
            List<UserOrg> userOrgs=userAuthorityService.getUserOrgByOpenid(openId);//加入农场
            List<UserOrg> followOrgs = userAuthorityService.getFollowUserOrgByOpenId(openId);//关注农场
            authUserDto.setJoinUserOrg(userOrgs);
            authUserDto.setFollowUserOrg(followOrgs);

        } catch (Exception e) {
            return new HttpResponseEntity<AuthUserDto>(new Error().error("sql_error").errorDescription(e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }

        return new HttpResponseEntity<AuthUserDto>(authUserDto, HttpStatus.OK);
    }


    @Override
    public HttpResponseEntity<Paginator<List<AuthUserDto>>> userNotShareholderGet(
            @ApiParam(value = "用户名或者手机号", required = false) @RequestParam(value = "key", required = false) String key,
            @ApiParam(value = "是否是贫困户", required = false) @RequestParam(value = "isPoor", required = false) String isPoor,
            @ApiParam(value = "当前页", required = true) @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(value = "每页大小", required = true) @RequestParam(value = "pageSize", required = true) Integer pageSize) {

        String clientId=OAuth2AuthenticationImpl.clientId();
        //logger.info("clientId="+clientId);
//        logger.info("isShareholder="+isShareholder);
//        if(StringUtils.isEmpty(isShareholder)||"0".equals(isShareholder)){
//            isShareholder=null;
//        }
//        logger.info("isShareholder1="+isShareholder);
        logger.info("key="+key+",page="+page+",pageSize="+pageSize);
        PagesUtil pagesUtil= null;
        List<AuthUserDto> authUsers= null;
        String isShakePoverty=null;
        if(!StringUtils.isEmpty(isPoor)){
            isShakePoverty=("0".equals(isPoor)?"1":"0");
        }
        List<AuthUserDto> authUserDtosRes=new ArrayList<>();
        List<AuthUserDto> authUserDtosResFinal=new ArrayList<>();
        try {
            int totalCount=userAuthorityService.getCountNotShareholderAuthUser(clientId,key,isShakePoverty);
            logger.info("totalCount="+totalCount);
            if(totalCount<=0){
                totalCount=0;
            }
            pagesUtil = new PagesUtil();
            pagesUtil.setPageSize(pageSize);
            pagesUtil.setTotalCount(totalCount);
            pagesUtil.setCurrentPage(page);
            if(page<1){
                pagesUtil.setCurrentPage(1);
            }
            Map<String,AuthUserDto> authUsersMap=new HashMap();
            logger.info("clientId="+clientId+",key="+key+",isShakePoverty="+isShakePoverty+",key="+key+",page="+page+",pageSize="+pageSize);
            authUsers = userAuthorityService.getNotShareholderAuthUser(clientId,key,isShakePoverty,(pagesUtil.getCurrentPage()-1)*pageSize,pageSize);

            logger.info("authUsers="+authUsers);
           for(AuthUserDto authUserDto:authUsers){
               authUsersMap.put(authUserDto.getUserId(),authUserDto);
           }
            Collection<AuthUserDto> valueCollection = authUsersMap.values();
             authUserDtosRes=new ArrayList<>(valueCollection);
            //logger.info("authUsers="+authUsers);
            if(null!=valueCollection&&(valueCollection.size()>(pagesUtil.getCurrentPage()-1)*pageSize)){
                int start=(pagesUtil.getCurrentPage()-1)*pageSize;
                if(valueCollection.size()>(start+pageSize)){
                    for(int i=start;i<(start+pageSize);i++){//authUserDtosResFinal
                        authUserDtosResFinal.add(authUserDtosRes.get(i));
                    }
                }else{
                    for(int i=start;i<valueCollection.size();i++){
                        authUserDtosResFinal.add(authUserDtosRes.get(i));
                    }
                }

            }
            for(AuthUserDto authUserDto:authUserDtosResFinal){
               // logger.info("authUserDto="+authUserDto);
                if(null!=authUserDto&&!StringUtils.isEmpty(authUserDto.getAddressCode())){
                 //   logger.info("addressCode="+authUserDto.getAddressCode());
                   // logger.info("address="+getAllAddress(authUserDto.getAddressCode()));
                    authUserDto.setAddressCode(getAllAddress(authUserDto.getAddressCode()));
                }

            }

            //logger.info("authUsers1="+authUsers);
        } catch (Exception e) {
            return new HttpResponseEntity<>(new Error().error("sql_error").errorDescription(e.getMessage()), HttpStatus.BAD_REQUEST);
        }
        logger.info("authUserDtosRes="+authUserDtosRes);
        Paginator<List<AuthUserDto>> paginators=new Paginator<List<AuthUserDto>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                pagesUtil.getTotalCount(),authUserDtosResFinal);

        return new HttpResponseEntity<Paginator<List<AuthUserDto>>>(paginators, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<Paginator<List<AuthUserDto>>> userNotempGet(
            @ApiParam(value = "用户名或者手机号", required = false) @RequestParam(value = "key", required = false) String key,
            @ApiParam(value = "是否是贫困户", required = false) @RequestParam(value = "isPoor", required = false) String isPoor,
            @ApiParam(value = "当前页", required = true) @RequestParam(value = "page", required = true) Integer page
            , @ApiParam(value = "每页大小", required = true) @RequestParam(value = "pageSize", required = true) Integer pageSize) {

        String clientId=OAuth2AuthenticationImpl.clientId();
        logger.info("clientId="+clientId);
//        logger.info("isShareholder="+isShareholder);
//        if(StringUtils.isEmpty(isShareholder)||"0".equals(isShareholder)){
//            isShareholder=null;
//        }
//        logger.info("isShareholder1="+isShareholder);
        logger.info("key="+key+",page="+page+",pageSize="+pageSize);
        PagesUtil pagesUtil= null;
        List<AuthUserDto> authUsers= null;
        List<AuthUserDto> authUserDtosRes=null;
        List<AuthUserDto> authUserDtosResFinal=new ArrayList<>();
        String isShakePoverty=null;
        if(!StringUtils.isEmpty(isPoor)){
             isShakePoverty=("0".equals(isPoor)?"1":"0");
        }

        try {
            int totalCount=userAuthorityService.getCountNotEmpAuthUser(clientId,key,isShakePoverty);
            logger.info("totalCount="+totalCount);
            if(totalCount<=0){
                totalCount=0;
            }
            pagesUtil = new PagesUtil();
            pagesUtil.setPageSize(pageSize);
            pagesUtil.setTotalCount(totalCount);
            pagesUtil.setCurrentPage(page);
            if(page<1){
                pagesUtil.setCurrentPage(1);
            }
            Map<String,AuthUserDto> authUsersMap=new HashMap();
            authUsers = userAuthorityService.getNotEmpAuthUser(clientId,key,isShakePoverty,(pagesUtil.getCurrentPage()-1)*pageSize,pageSize);
            for(AuthUserDto authUserDto:authUsers){
                authUsersMap.put(authUserDto.getUserId(),authUserDto);
            }
            Collection<AuthUserDto> valueCollection = authUsersMap.values();
            authUserDtosRes=new ArrayList<>(valueCollection);

            logger.info("authUsers="+authUsers);
            if(null!=valueCollection&&(valueCollection.size()>(pagesUtil.getCurrentPage()-1)*pageSize)){
                int start=(pagesUtil.getCurrentPage()-1)*pageSize;
                if(valueCollection.size()>(start+pageSize)){
                    for(int i=start;i<(start+pageSize);i++){//authUserDtosResFinal
                        authUserDtosResFinal.add(authUserDtosRes.get(i));
                    }
                }else{
                    for(int i=start;i<valueCollection.size();i++){
                        authUserDtosResFinal.add(authUserDtosRes.get(i));
                    }
                }

            }
            for(AuthUserDto authUserDto:authUserDtosResFinal){
                logger.info("authUserDto="+authUserDto);
                if(null!=authUserDto&&!StringUtils.isEmpty(authUserDto.getAddressCode())){
                    logger.info("addressCode="+authUserDto.getAddressCode());
                    logger.info("address="+getAllAddress(authUserDto.getAddressCode()));
                    authUserDto.setAddressCode(getAllAddress(authUserDto.getAddressCode()));
                }

            }

            //logger.info("authUsers1="+authUsers);
        } catch (Exception e) {
            return new HttpResponseEntity<>(new Error().error("sql_error").errorDescription(e.getMessage()), HttpStatus.BAD_REQUEST);
        }

        Paginator<List<AuthUserDto>> paginators=new Paginator<List<AuthUserDto>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                pagesUtil.getTotalCount(),authUserDtosResFinal);

        return new HttpResponseEntity<Paginator<List<AuthUserDto>>>(paginators, HttpStatus.OK);

    }

    @Override
    public HttpResponseEntity<AuthUserDto> userEmployerGet() {
        String clientId=OAuth2AuthenticationImpl.clientId();
        AuthUserDto authUserDto= null;
        try {
            authUserDto = organizationService.getMyFarmerUser(clientId);
        } catch (Exception e) {
            return new HttpResponseEntity<>(new Error().error("sql_error").errorDescription(e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }
        return new HttpResponseEntity<AuthUserDto>(authUserDto, HttpStatus.OK);
    }

    /**
     * 根据clientId查询用户信息
     * @param clientId
     * @return
     */
    @Override
    public HttpResponseEntity<AuthUser> userInfoByClientGet(@ApiParam(value = "clientid", required = true) @PathVariable String clientId) {

        AuthUser authUser=userAuthorityService.getAuthUserByClientId(clientId);
        return new HttpResponseEntity<AuthUser>(authUser, HttpStatus.OK);
    }

    /**
     * 修改用户信息
     * @param authUser
     * @return
     */
    @Override
    public HttpResponseEntity<Integer> userInfoUsingPUT(@ApiParam(value = "authUser", required = true) @RequestBody AuthUser authUser) {
        if(userAuthorityService.getUserPhoneNumberCount(authUser.getPhoneNumber())>=1){
            Error error = new Error().error("phone_number_is_exists").errorDescription("phone number is xists");
            return new HttpResponseEntity<Integer>(error, HttpStatus.BAD_REQUEST);
        }
        if(null!=authUser.getPhoneNumber()){
            int count=userAuthorityService.updateAuthUser(authUser);
            return new HttpResponseEntity<Integer>(count, HttpStatus.OK);
        }else {
            int count = userAuthorityService.updateSitUser(authUser);
            return new HttpResponseEntity<Integer>(count, HttpStatus.OK);
        }
    }

    @Override
    public HttpResponseEntity<String> settingHeadImagesPUT(
            @ApiParam(value = "头像", required = true) @RequestParam String headImg
    ) {
        Integer count=null;

        try {
            String openId =OAuth2AuthenticationImpl.openId();
            count= userAuthorityService.updateMyHeadImg(headImg,openId);
        }catch (Exception ex){
            return new HttpResponseEntity<String>(new Error().error("sql_error").errorDescription(ex.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }

        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> settingNamePUT(
            @ApiParam(value = "姓名", required = true) @RequestParam String name,
            @ApiParam(value = "身份证", required = false) @RequestParam(required = false) String idCard,
            @ApiParam(value = "身份证照片", required = true) @RequestParam(required = false) String idCardImg
    ) {
        Integer count=null;

        if(userAuthorityService.getUseridCardCount(idCard)>=1){
            Error error = new Error().error("id_card_is_exists").errorDescription("id_card is exists");
            return new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
        }
        try {
            String openId =OAuth2AuthenticationImpl.openId();
            count= userAuthorityService.updateName(name,openId);
            if(!StringUtils.isEmpty(idCard)){
                userAuthorityService.updateMyIdCard(idCard,idCardImg,openId);
            }
        }catch (Exception ex){
            return new HttpResponseEntity<String>(new Error().error("id_card is exists").errorDescription(ex.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }

        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> settingPhonePUT(
            @ApiParam(value = "电话号码", required = true) @RequestParam(required = true) String newPhoneNumber,
            @ApiParam(value = "旧手机验证码", required = true) @RequestParam(required = true) String oldVerifyCode,
            @ApiParam(value = "新手机验证码", required = true) @RequestParam(required = true) String newVerifyCode,
            HttpServletRequest request
    ) {
        Integer count=null;
        Error error = null;


        if(!request.getSession().getAttribute(verify_code_me_key).equals(oldVerifyCode)){
            error=new Error().error("check_code").errorDescription("old verify code is not right");
            return new HttpResponseEntity<String>(error,HttpStatus.BAD_REQUEST);
        }

        /**验证新手机验证  设置新手机号*/
        if(userAuthorityService.getUserPhoneNumberCount(newPhoneNumber)>=1){
            error = new Error().error("phone_number_is_exists").errorDescription("phone number is exists");
            return new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
        }
        if((new Date().getTime() - ((Date) request.getSession().getAttribute(verify_code_date)).getTime()) > verify_code_timeout * 60000){
            error=new Error().error("invalid_param").errorDescription("verify code timeout");
            return new HttpResponseEntity<String>(error,HttpStatus.BAD_REQUEST);
        }

        if(!request.getSession().getAttribute(verify_code_key).equals(newPhoneNumber+newVerifyCode)){
            error=new Error().error("check_code").errorDescription("new verify code is not right");
            return new HttpResponseEntity<String>(error,HttpStatus.BAD_REQUEST);
        }

        try {
            String openId =OAuth2AuthenticationImpl.openId();
            count= userAuthorityService.updatePhone(newPhoneNumber,openId);
        }catch (Exception ex){
            return new HttpResponseEntity<String>(new Error().error("sql error！").errorDescription(ex.getLocalizedMessage()),HttpStatus.INSUFFICIENT_STORAGE);
        }

        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> settingAddressPUT(
            @ApiParam(value = "地址代码", required = true) @RequestParam String addressCode,
            @ApiParam(value = "地址详情", required = true) @RequestParam String addressDetail
    ) {
        Integer count=null;

        try {
            String openId =OAuth2AuthenticationImpl.openId();
            count= userAuthorityService.updateAddress(addressCode,addressDetail,openId);
        }catch (Exception ex){
            return new HttpResponseEntity<String>(new Error().error("sql_error").errorDescription(ex.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
        }

        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> checkOldPwdPUT(
            @ApiParam(value = "原密码", required = true) @RequestParam String oldPassword
    ) {
        Integer count=null;

       try {
           String openId =OAuth2AuthenticationImpl.openId();
           count= userAuthorityService.selectPassword(oldPassword, openId);
       }catch (Exception ex){
           return new HttpResponseEntity<String>(new Error().error("sql_error").errorDescription(ex.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
       }

        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> verifyCodePUT(
            @ApiParam(value = "验证码", required = true) @RequestParam String verifyCode,
            HttpServletRequest request
    ) {

        //获取存在session的验证码
        String newSessionCode= (String) request.getSession().getAttribute(verify_code_key);
        String oldSessionCode= (String) request.getSession().getAttribute(verify_code_me_key);
        if(newSessionCode!=null||oldSessionCode!=null){
            if (verifyCode.equalsIgnoreCase(newSessionCode)||verifyCode.equalsIgnoreCase(oldSessionCode)){
                return new HttpResponseEntity<String>(1+"",HttpStatus.OK);
            }
        }
        return new HttpResponseEntity<String>(0+"",HttpStatus.OK);
    }

    /**
     * 遍历集合查询用户信息
     * @param openIdList
     * @return
     */
    @Override
    public HttpResponseEntity<List<UserDto>> UserMeInfoPUT(
            @ApiParam(value = "openId数组", required = true) @RequestParam("openIdList") String openIdList) {

        List<UserDto> userDtos = new ArrayList<>();

        logger.info("----openId:"+openIdList);
        JSONArray jsonArray = JSONArray.fromObject(openIdList);
        List<String> list= jsonArray.toList(jsonArray, String.class);
        for (int i = 0;i<list.size();i++){//遍历取出openId  并查询出相应的用户信息
               String openid=list.get(i);
                logger.info("----userDto:"+openid);
                UserDto userDto = userAuthorityService.getUserInfoByOpenId(openid);
                logger.info("----userDto:"+userDto);
                userDtos.add(userDto);
            }

        return new HttpResponseEntity<List<UserDto>>(userDtos,HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<List<String>> QueryOrgIdPOST() {
        String openId = OAuth2AuthenticationImpl.openId();

        List<String> clientIdList = null;
        try {
            clientIdList  = dbUserDetailsService.getAllClientIdByOpenId(openId);
        } catch (Exception e) {
            return new HttpResponseEntity<List<String>>(new Error().errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }
        return new HttpResponseEntity<List<String>>(clientIdList,HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> PunchClockPOST(  @ApiParam(value = "打卡对象，userId，时间可不传后台获取", required = true) @RequestBody PunchClock punchClock) {
        String openId = OAuth2AuthenticationImpl.openId();

        try {
            //判断今日是否已打卡
            if(userAuthorityService.getTodayPunchClock(openId)>=1){
                return new HttpResponseEntity(new Error().error("to_day_is_punch_the_clock").errorDescription("今日已打卡，不能再打了"),HttpStatus.BAD_GATEWAY);
            }
            punchClock.setId(UUID.randomUUID().toString());
            punchClock.setUserId(OAuth2AuthenticationImpl.openId());
            int clock = userAuthorityService.insertPunchClock(punchClock);
            return new HttpResponseEntity<String>(clock+"",HttpStatus.OK);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }

    }

    @Override
    public HttpResponseEntity<Map> PunchClockGET(
            @ApiParam(value = "开始页码", required = true) @RequestParam int start,
            @ApiParam(value = "页面大小", required = true) @RequestParam int size
    ) {

        Map<String,Object> map = new HashedMap();
        Paginator<List<PunchClock>> paginator = null;


        try {
            String openId = OAuth2AuthenticationImpl.openId();
            int totalCount=userAuthorityService.getPunchTheClockInfoCount(openId);
            logger.info("totalCount="+totalCount);
            if(totalCount<=0){
                totalCount=0;
            }
            PagesUtil pagesUtil = new PagesUtil();
            pagesUtil.setPageSize(size);
            pagesUtil.setTotalCount(totalCount);
            pagesUtil.setCurrentPage(start);
            if(start<1){
                pagesUtil.setCurrentPage(1);
            }
            List<PunchClock> punchClocks = userAuthorityService.getPunchTheClockInfo(openId,pagesUtil.getStartPage(),size);
            paginator  = new Paginator<List<PunchClock>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),punchClocks);
            //查询本月打卡天数
            int mouthNumber = userAuthorityService.getToMouthPunchDayNumber(openId);
            //查询今日是否已打卡
            int isPunch = userAuthorityService.getTodayPunchClock(openId);
            map.put("mouthPunchNumber",mouthNumber);
            map.put("isPunch",isPunch);
            map.put("punchClocks",punchClocks);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }

        return new HttpResponseEntity<Map>(map,HttpStatus.OK);
    }


    private String getAllAddress(String addressCode) {
        String farmAdress="";
        if(StringUtils.isEmpty(addressCode)){
            return null;
        }
        Map<String,String> geoCodingsMap= CommonUtil.parseGeoCodings(addressCode);
        String  city=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("city"))==null?"":geoCodingsService.getGeoCodingsById(geoCodingsMap.get("city")).getGeoName();
        String  county=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("county"))==null?"":geoCodingsService.getGeoCodingsById(geoCodingsMap.get("county")).getGeoName();
        String  vilage=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("vilage"))==null?"":geoCodingsService.getGeoCodingsById(geoCodingsMap.get("vilage")).getGeoName();
        String  burg=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("burg"))==null?"":geoCodingsService.getGeoCodingsById(geoCodingsMap.get("burg")).getGeoName();
        if(!StringUtils.isEmpty(city)){
            farmAdress+=city;
        }
        if(!StringUtils.isEmpty(county)){
            farmAdress+=county;
        }
        if(!StringUtils.isEmpty(vilage)){
            farmAdress+=vilage;
        }
        if(!StringUtils.isEmpty(burg)){
            farmAdress+=burg;
        }
        return farmAdress;
    }
}
